package com.dd;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.dd.exception.UnauthorizedException;
import com.javapig.util.StringUtils;

public class AuthorizationFactory {
	private static final Logger logger = Logger.getLogger(	AuthorizationFactory.class.getName());
	/** DATABASE QUERIES * */
	private static final String AUTHORIZE = "select YuanGongId,DengJi from YuanGongInfoTable";

	/**
	 * The same token can be used for all anonymous users, so cache it.
	 */
	private static final Authorization anonymousAuth = new Authorization(-1);

	
	public static Authorization createAuthorization(String username, String password)
			throws UnauthorizedException {
		logger.debug("enter createAuthorization() method");
		logger.debug("input username:"+username+" and password:"+password);
		if (username == null || password == null) {
			throw new UnauthorizedException("用户名或密码不能为空");
		}
		//MD5加密 可以根据用户需要执行
		//StringUtils.hash(password)
		//password = StringUtils.hash(password);
		int userID,level = -1;
		DBUtil2 du2 = DBUtil2.getDefaultDBUtil2();
		//查询条件
		Map whereFields = new HashMap();
		whereFields.put("YongHuMing", username);
		whereFields.put("MiMa", password);
		Map m_rowData = du2.getRow(AUTHORIZE, whereFields);
		if (m_rowData == null || m_rowData.size()<1){
			logger.error("wrong username or password");
			throw new  UnauthorizedException("用户名或密码错误");
		}
		userID = ( (Integer)m_rowData.get("YuanGongId") ).intValue();
		level = ( (Integer)m_rowData.get("DengJi") ).intValue();

		// Got this far, so the user must be authorized.
		return new Authorization(userID,level);
	}

	/**
	 * Creates anonymous Authorization tokens.
	 * 
	 * @return an anonymous Authorization token.
	 */
	public Authorization createAnonymousAuthorization() {
		return anonymousAuth;
	}
}
